from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
import json
from app.libs.error_code import AuthFailed
from app.config import SECRET_KEY



def generate_token(uid, ac_type, auth=None,expiration=7200):
    # token
    s = Serializer(SECRET_KEY, expires_in=expiration)   # 序列化器
    return s.dumps({
        'uid': uid,
        'type': ac_type,
        'auth':auth
    })

def decode_token(_token):
    # 解密 token

    s = Serializer(SECRET_KEY)    # 序列化器
    try:
        data = s.loads(_token, return_header=True)
    except SignatureExpired:
        raise AuthFailed(msg='token is expired', error_code=1003)
    except BadSignature:
        raise AuthFailed(msg='token is invalid', error_code=1002)
  
    # ({'uid': 1, 'type': 'pc', 'auth': 1}, {'alg': 'HS512', 'iat': 1619763915, 'exp': 1619771115})
    r = {
        "auth": data[0]['auth'],
        "type": data[0]['type'],
        "uid": data[0]['uid']
    }
    return json.dumps(r)
